/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.base.redis.web;

import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.base.domain.vo.ResultVO;
import com.iwindplus.base.redis.domain.vo.RedisCacheInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 缓存监控相关操作接口定义类.
 *
 * @author zengdegui
 * @since 2020/9/20
 */
@Tag(name = "缓存监控接口")
@Slf4j
@RestController
@RequestMapping("redisCache")
@Validated
public class RedisCacheController {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * redis缓存监控信息.
     *
     * @return ResultVO<RedisCacheInfoVO>
     */
    @Operation(summary = "redis缓存监控信息")
    @GetMapping("getInfo")
    public ResultVO<RedisCacheInfoVO> getInfo() {
        RedisConnection connection = redisConnectionFactory.getConnection();
        Properties commandStats = connection.commands().info("commandstats");
        List<Map<String, String>> pieList = new ArrayList<>();
        if (commandStats != null) {
            commandStats.stringPropertyNames().forEach(key -> {
                Map<String, String> data = new HashMap<>(2);
                String property = commandStats.getProperty(key);
                data.put("name", CharSequenceUtil.removePrefix(key, "cmdstat_"));
                data.put("value", CharSequenceUtil.subBetween(property, "calls=", ",usec"));
                pieList.add(data);
            });
        }
        RedisCacheInfoVO data =
            RedisCacheInfoVO.builder()
                .info(connection.commands().info())
                .dbSize(connection.commands().dbSize())
                .commandStats(pieList)
                .build();
        return ResultVO.success(data);
    }
}
